#!/bin/bash
# Ambari Cluster Status Script
# Usage: ./ambari-status.sh

set -e

# 配置参数
AMBARI_SERVER="hadoop-app"
SSH_USER="root"
SSH_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=5"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

check_host_status() {
    local host=$1
    local service=$2
    
    if ssh $SSH_OPTS $SSH_USER@$host "systemctl is-active $service" &>/dev/null; then
        echo -e "${GREEN}✓${NC} $host: $service 运行中"
    else
        echo -e "${RED}✗${NC} $host: $service 未运行"
    fi
}

# 检查所有节点状态
check_all_status() {
    echo "=== Ambari集群状态检查 ==="
    echo
    
    # 检查Ambari Server
    check_host_status $AMBARI_SERVER "ambari-server"
    echo
    
    # 检查Ambari Agents
    local hosts=("hadoop-app" "hadoop-node1" "hadoop-node2" "hadoop-node3")
    for host in "${hosts[@]}"; do
        check_host_status $host "ambari-agent"
    done
}

# 检查系统资源
check_system_resources() {
    echo
    echo "=== 系统资源状态 ==="
    
    local hosts=("hadoop-app" "hadoop-node1" "hadoop-node2" "hadoop-node3")
    for host in "${hosts[@]}"; do
        echo "--- $host ---"
        ssh $SSH_OPTS $SSH_USER@$host "
            echo '内存使用:'
            free -h | head -2
            echo
            echo '磁盘使用:'
            df -h / /var /tmp | grep -v tmpfs
            echo
            echo 'CPU使用率:'
            top -bn1 | head -5 | tail -2
            echo
        " 2>/dev/null || echo "无法获取 $host 资源信息"
        echo
    done
}

main() {
    check_all_status
    check_system_resources
}

main "$@"
